package cn.rxls.community.util;

import cn.rxls.community.contant.JwtConstant;
import cn.rxls.community.enums.ResultEnum;
import cn.rxls.community.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * http工具类
 */
public class HttpUtil {


    //获取http信息
    public static HttpServletRequest getHttpInfo() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    //获取令牌包含的用户信息
    public static Map<String, Object> getUserLoginInfo(HttpServletRequest request) {
        String token = request.getHeader(JwtConstant.ACCESS_TOKENS);
        if(Objects.isNull(token) || token.equals("")){
           throw new BusinessException(ResultEnum.ERROR_LOGIN_NOT);
        }
        Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
        if (Objects.isNull(stringObjectMap)) {
            throw new BusinessException(ResultEnum.ERROR_LOGIN);
        }
        return stringObjectMap;
    }

    //获取令牌包含的用户信息
    public static Map<String, Object> getUserLoginInfo() {
        return getUserLoginInfo(getHttpInfo());
    }
}
